package net.hn.hnms.biz.mine.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import net.hn.hnms.biz.api.safety.dust.fegin.RemoteDustService;
import net.hn.hnms.biz.api.safety.fire.fegin.RemoteFrieService;
import net.hn.hnms.biz.api.safety.location.fegin.RemoteLocationService;
import net.hn.hnms.biz.api.safety.monitor.fegin.RemoteMonitorService;
import net.hn.hnms.biz.api.safety.monitor.model.BaseSensorCoordDto;
import net.hn.hnms.biz.api.safety.support.fegin.RemoteSupportService;
import net.hn.hnms.biz.api.safety.water.fegin.RemoteWaterService;
import net.hn.hnms.biz.mine.domain.*;
import net.hn.hnms.biz.mine.domain.*;
import net.hn.hnms.biz.mine.domain.dto.CoverageDto;
import net.hn.hnms.biz.mine.domain.dto.DefinedSensorDto;
import net.hn.hnms.biz.mine.domain.vo.CoverageDeviceListVo;
import net.hn.hnms.biz.mine.domain.vo.CoverageListVo;
import net.hn.hnms.biz.mine.domain.vo.CoverageSystemListVo;
import net.hn.hnms.biz.mine.domain.vo.CoverageTreeListVo;
import net.hn.hnms.biz.mine.mapper.*;
import net.hn.hnms.biz.mine.mapper.*;
import net.hn.hnms.biz.mine.service.CoverageService;
import net.hn.hnms.biz.mine.vo.*;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.core.utils.StringUtils;
import net.hn.hnms.sys.common.redis.utils.RedisUtils;
import net.hn.hnms.sys.system.api.domain.SysDictData;
import net.hn.hnms.biz.mine.vo.*;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 图层标注实现类
 */
@Service
public class CoverageServiceImpl implements CoverageService {
    //远程调用安全监控MonitorService服务
    @Resource
    private RemoteMonitorService remoteMonitorService;
    //远程调用人员定位LocationService服务
    @Resource
    private RemoteLocationService remoteLocationService;
    //远程调用火灾防治束管FrieService服务
    @Resource
    private RemoteFrieService remoteFrieService;
    //远程调用水害监测WaterService服务
    @Resource
    private RemoteWaterService remoteWaterService;
    //远程调用粉尘监测DustService服务
    @Resource
    private RemoteDustService remoteDustService;

    //远程调用矿压监测（顶板离层，锚杆所，支架）SupportService服务
    @Resource
    private RemoteSupportService remoteSupportService;
    //图层系统测点标记坐标配置Mapper
    @Resource
    private CoverageSensorMarkerMapper coverageSensorMarkerMapper;
    //图层系统图层测点信息记录表Mapper
    @Resource
    private CoverageSensorRecordMapper coverageSensorRecordMapper;

    //图层系统图层信息记录Mapper
    @Resource
    private CoverageSensorLayerMapper coverageSensorLayerMapper;

    /**
     * 自定义测点表
     */
    @Resource
    private CoverageSensorDefinedMapper coverageSensorDefinedMapper;

    @Resource
    private CoverageSystemInfoMapper coverageSystemInfoMapper;

    /**
     * 根据系统类型获取测点列表
     *
     * @param osType
     * @return
     */
    @Override
    public List<BaseSensorVo> getBaseListByType(String osType, String mineCode, String companyCode) {
        List<BaseSensorVo> voList = null;
        //获取测点标记配置表
        LambdaQueryWrapper<CoverageSensorMarkerPo> queryWrapper = new LambdaQueryWrapper<>();
        //系统编码
        queryWrapper.eq(CoverageSensorMarkerPo::getSystemCode, osType);
        //煤矿编码
        queryWrapper.eq(StringUtils.isNotBlank(mineCode), CoverageSensorMarkerPo::getMineCode, mineCode);
        //查询出来所有的安全监控的集合
        List<CoverageSensorMarkerPo> coverageSensorMarkerPos = coverageSensorMarkerMapper.selectList(queryWrapper);
        if ("1".equals(osType)) {
            //远程获取安全监控的数据
            try {
                List<BaseSensorCoordDto> baseSensorTableAllList = remoteMonitorService.getBaseSensorTableAllList(mineCode, companyCode);
                voList = getBaseSensorVoList(baseSensorTableAllList, coverageSensorMarkerPos);
            } catch (Exception e) {
                System.out.println("远程获取安全监控的数据出错");
            }
            //类型转换
        } else if ("2".equals(osType)) {
            //远程获取人员定位的数据
            try {

                List<BaseSensorCoordDto> baseSensorTableAllList = remoteLocationService.getBaseSensorTableAllList(mineCode, companyCode);
                //类型转换
                voList = getBaseSensorVoList(baseSensorTableAllList, coverageSensorMarkerPos);
            } catch (Exception e) {
                System.out.println("远程获取人员定位的数据出错");
            }
        } else if ("3".equals(osType)) {
            //远程获取水文监测系统的数据(长观孔，涌水点，排水点)
            try {
                List<BaseSensorCoordDto> baseSensorTableAllList = remoteWaterService.getBaseSensorTableAllList(mineCode, companyCode);
                voList = getBaseSensorVoList(baseSensorTableAllList, coverageSensorMarkerPos);
            } catch (Exception e) {
                System.out.println("远程获取水文监测系统的数据出错");
            }
        } else if ("4".equals(osType)) {
            //远程获取束管监测系统的数据
            try {
                List<BaseSensorCoordDto> baseSensorTableAllList = remoteFrieService.getSgjcBaseSensorTableAllList(mineCode, companyCode);
                voList = getBaseSensorVoList(baseSensorTableAllList, coverageSensorMarkerPos);
            } catch (Exception e) {
                System.out.println("远程获取束管监测系统的数据出错");
            }

        } else if ("5".equals(osType)) {
            //远程获取光纤测温系统的数据


        } else if ("6".equals(osType)) {
            //远程获取视频监控系统的数据


        } else if ("7".equals(osType)) {
            //远程获取液压支架系统的数据(生产监控)
            try {
                List<BaseSensorCoordDto> baseSensorTableAllList = remoteSupportService.getProductionZjjcBaseSensorTableAllList(mineCode, companyCode);
                voList = getBaseSensorVoList(baseSensorTableAllList, coverageSensorMarkerPos);
            } catch (Exception e) {
                System.out.println("远程获取液压支架系统的数据(生产监控)出错");
            }
        } else if ("8".equals(osType)) {
            //远程获取矿压监测系统的数据（冲击地压）
            try {
                List<BaseSensorCoordDto> baseSensorTableAllList = remoteSupportService.getKyjcBaseSensorTableAllList(mineCode, companyCode);
                voList = getBaseSensorVoList(baseSensorTableAllList, coverageSensorMarkerPos);

            } catch (Exception e) {
                System.out.println("远程获取矿压监测系统的数据（冲击地压）出错");
            }
        } else if ("9".equals(osType)) {
            //远程获取粉尘监测系统的数据
            try {
                List<BaseSensorCoordDto> baseSensorTableAllList = remoteDustService.getBaseSensorTableAllList(mineCode, companyCode);
                voList = getBaseSensorVoList(baseSensorTableAllList, coverageSensorMarkerPos);
            } catch (Exception e) {
                System.out.println("远程获取粉尘监测系统的数据出错");
            }
        } else if ("10".equals(osType)) {
            try {
                //远程获取钻孔应力系统的数据
                List<BaseSensorCoordDto> baseSensorTableAllList = remoteSupportService.getZkylBaseSensorTableAllList(mineCode, companyCode);
                voList = getBaseSensorVoList(baseSensorTableAllList, coverageSensorMarkerPos);
            } catch (Exception e) {
                System.out.println("远程获取钻孔应力系统的数据出错");
            }

        } else if ("11".equals(osType)) {
            //远程获取地音系统的数据


        } else if ("12".equals(osType)) {
            //远程获取微震系统的数据


        } else if ("13".equals(osType)) {
            //远程获取边坡系统的数据


        } else if ("14".equals(osType)) {
            //远程获取其他系统的数据
            //获取自定义点位

        }

        if (voList == null) {
            return new ArrayList<>();
        }
        return voList;
    }

    @NotNull
    private static List<BaseSensorVo> getBaseSensorVoList(List<BaseSensorCoordDto> baseSensorTableAllList, List<CoverageSensorMarkerPo> coverageSensorMarkerPos) {
        List<BaseSensorVo> voList;
        voList = baseSensorTableAllList.stream().map(t -> {
            BaseSensorVo baseSensorVo = new BaseSensorVo();
            //测点编码
            baseSensorVo.setPointCode(t.getPointCode());
            //测点名称
            baseSensorVo.setPointName(t.getLocation());
            //测点类型编码
            baseSensorVo.setSensorTypeCode(t.getSensorTypeCode());
            //测点类型名称
            baseSensorVo.setSensorTypeName(t.getSensorTypeName());
            //x  保留9位，直接删除多余的位数
            baseSensorVo.setCoordinateX(t.getXCoordinate()==null?null:t.getXCoordinate().setScale(9, BigDecimal.ROUND_DOWN));
            //y
            baseSensorVo.setCoordinateY(t.getYCoordinate()==null?null:t.getYCoordinate().setScale(9, BigDecimal.ROUND_DOWN));
            //z
            baseSensorVo.setCoordinateZ(t.getZCoordinate()==null?null:t.getZCoordinate().setScale(9, BigDecimal.ROUND_DOWN));
            //遍历当前系统配置表配置表
            for (CoverageSensorMarkerPo coverageSensorMarkerPo : coverageSensorMarkerPos) {
                if (baseSensorVo.getPointCode().equals(coverageSensorMarkerPo.getPointCode())) {
                    //测点编码相同
                    //打上标记 已标记新坐标
                    baseSensorVo.setImportant(true);
                    //保留两位，直接删除多余的位数
                    baseSensorVo.setMarkedX(coverageSensorMarkerPo.getMarkedX()==null?null:coverageSensorMarkerPo.getMarkedX().setScale(9, BigDecimal.ROUND_DOWN));
                    baseSensorVo.setMarkedY(coverageSensorMarkerPo.getMarkedY()==null?null:coverageSensorMarkerPo.getMarkedY().setScale(9, BigDecimal.ROUND_DOWN));
                    baseSensorVo.setMarkedZ(coverageSensorMarkerPo.getMarkedZ()==null?null:coverageSensorMarkerPo.getMarkedZ().setScale(9, BigDecimal.ROUND_DOWN));
                    //已记录的测点名称
                    baseSensorVo.setMarkerPointName(coverageSensorMarkerPo.getPointName());
                    //判断原系统测点名称与已经记录的测点名称是否有差异差异
                    baseSensorVo.setDifferenceName(!t.getLocation().equals(coverageSensorMarkerPo.getPointName()));
                }
            }
            if (baseSensorVo.getImportant() == null) {
                baseSensorVo.setImportant(false);
            }
            return baseSensorVo;
        }).collect(Collectors.toList());
        return voList;
    }

    /**
     * 更新测点坐标
     *
     * @param baseSensorDto
     * @return
     */
    @Override
    public Boolean UpDataSensorCoordinate(BaseSensorDto baseSensorDto) {
//        //先查询是否已经存在
        LambdaQueryWrapper<CoverageSensorMarkerPo> queryWrapper = new LambdaQueryWrapper<>();
        //系统编码
        queryWrapper.eq(CoverageSensorMarkerPo::getSystemCode, baseSensorDto.getSystemTypeCode());
        //测点编码
        queryWrapper.eq(CoverageSensorMarkerPo::getPointCode, baseSensorDto.getPointCode());
        queryWrapper.eq(StringUtils.isNotBlank(baseSensorDto.getMineCode()),CoverageSensorMarkerPo::getMineCode, baseSensorDto.getMineCode());
        CoverageSensorMarkerPo coverageSensorMarkerPo = coverageSensorMarkerMapper.selectOne(queryWrapper);
        //获取图层系统类型字典编码
        List<SysDictData> coverageOSList = RedisUtils.getCacheObject(Constants.SYS_DICT_KEY + "biz_mineInfo_coverageOS_type");
        int update = 0;
        if (coverageSensorMarkerPo != null) {
            //不是空的 更新操作
            //x
            coverageSensorMarkerPo.setMarkedX(baseSensorDto.getMarkedX());
            //y
            coverageSensorMarkerPo.setMarkedY(baseSensorDto.getMarkedY());
            //z
            coverageSensorMarkerPo.setMarkedZ(baseSensorDto.getMarkedZ());
            update = coverageSensorMarkerMapper.update(coverageSensorMarkerPo, queryWrapper);
        } else {
            //新增操作
            coverageSensorMarkerPo = new CoverageSensorMarkerPo();
            //系统编码
            coverageSensorMarkerPo.setSystemCode(baseSensorDto.getSystemTypeCode());
            //系统名称
            if (!coverageOSList.isEmpty()) {
                //y有字典 读取字典值
                for (SysDictData sysDictData : coverageOSList) {
                    if (baseSensorDto.getSystemTypeCode().equals(sysDictData.getDictValue())) {
                        coverageSensorMarkerPo.setSystemName(sysDictData.getDictLabel());
                    }
                }
            } else {
                coverageSensorMarkerPo.setSystemName("字典出错，请检查字典");
            }
            //测点编码
            coverageSensorMarkerPo.setPointCode(baseSensorDto.getPointCode());
            //测点名称
            coverageSensorMarkerPo.setPointName(baseSensorDto.getPointName());
            //测点类型编码
            coverageSensorMarkerPo.setPointTypeCode(baseSensorDto.getSensorTypeCode());
            //测点类型名称
            coverageSensorMarkerPo.setPointTypeName(baseSensorDto.getSensorTypeName());
            //x
            coverageSensorMarkerPo.setMarkedX(baseSensorDto.getMarkedX());
            //y
            coverageSensorMarkerPo.setMarkedY(baseSensorDto.getMarkedY());
            //z
            coverageSensorMarkerPo.setMarkedZ(baseSensorDto.getMarkedZ());
            coverageSensorMarkerPo.setUpdateTime(new Date());
            coverageSensorMarkerPo.setMineCode(baseSensorDto.getMineCode()!=null?baseSensorDto.getMineCode():null);
            update = coverageSensorMarkerMapper.insert(coverageSensorMarkerPo);
        }
        if (update > 0) {
            return true;
        }

        return false;
    }

    /**
     * 删除测点坐标
     *
     * @param sensorCoordinateDto
     * @return
     */
    @Override
    public Boolean deleteSensorCoordinate(SensorCoordinateDto sensorCoordinateDto) {
        LambdaQueryWrapper<CoverageSensorMarkerPo> queryWrapper = new LambdaQueryWrapper<>();
        //系统
        queryWrapper.eq(CoverageSensorMarkerPo::getSystemCode, sensorCoordinateDto.getOsType());
        queryWrapper.eq(StringUtils.isNotBlank(sensorCoordinateDto.getMineCode()), CoverageSensorMarkerPo::getMineCode, sensorCoordinateDto.getMineCode());
        queryWrapper.in(!sensorCoordinateDto.getPointCodeList().isEmpty(), CoverageSensorMarkerPo::getPointCode, sensorCoordinateDto.getPointCodeList());
        int delete = coverageSensorMarkerMapper.delete(queryWrapper);
        if (delete > 0) {
            return true;
        }
        return false;
    }

    /**
     * 更新图层测点列表
     *
     * @param coverageSensorListDto
     * @return
     */
    @Override
    public Boolean UpDataCoverageSensorList(CoverageSensorListDto coverageSensorListDto) {
        //1.删除整个图层的数据
        if (coverageSensorListDto.getCoverageTypeCode() == null) {
            throw new HuaNengException(Constants.FAIL, "图层信息类型字典值不能为空");
        }
        coverageSensorRecordMapper.delete(new LambdaQueryWrapper<CoverageSensorRecordPo>()
                .eq(CoverageSensorRecordPo::getCoverageCode, coverageSensorListDto.getCoverageTypeCode())
                .eq(StringUtils.isNotBlank(coverageSensorListDto.getMineCode()), CoverageSensorRecordPo::getMineCode, coverageSensorListDto.getMineCode()));


        //系统类型
        List<SysDictData> coverageOSTypeList = RedisUtils.getCacheObject(Constants.SYS_DICT_KEY + "biz_mineInfo_coverageOS_type");
        //图层信息
        CoverageSensorLayerPo coverageSensorLayerPo = coverageSensorLayerMapper.selectOne(
                new LambdaQueryWrapper<CoverageSensorLayerPo>()
                        .eq(CoverageSensorLayerPo::getCoverageCode, coverageSensorListDto.getCoverageTypeCode())
                        .eq(StringUtils.isNotBlank(coverageSensorListDto.getMineCode()), CoverageSensorLayerPo::getMineCode, coverageSensorListDto.getMineCode()));
        //生成新的图层数据
        for (CoverageSystemListDto coverageSystemListDto : coverageSensorListDto.getCoverageSystemListDtos()) {
            //当前系统
            for (BaseSensorVo baseSensorVo : coverageSystemListDto.getBaseSensorVoList()) {
                //需要新增的测点
                CoverageSensorRecordPo coverageSensorRecordPo = new CoverageSensorRecordPo();
                //图层编码
                coverageSensorRecordPo.setCoverageCode(coverageSensorListDto.getCoverageTypeCode());
                //图层名称
                if (coverageSensorLayerPo != null) {
                    //将字典label注入图层名称
                    coverageSensorRecordPo.setCoverageName(coverageSensorLayerPo.getCoverageName());
                }
                //系统编码
                coverageSensorRecordPo.setSystemCode(coverageSystemListDto.getOsTypeCode());
                //系统名称
                if (coverageSystemListDto.getOsTypeLabel() != null) {
                    coverageSensorRecordPo.setSystemName(coverageSystemListDto.getOsTypeLabel());
                } else {
                    if (!coverageOSTypeList.isEmpty()) {
                        for (SysDictData sysDictData : coverageOSTypeList) {
                            //判断字典value和图层名称是否相符
                            if (coverageSystemListDto.getOsTypeCode().equals(sysDictData.getDictValue())) {
                                //将字典label注入图层名称
                                coverageSensorRecordPo.setSystemName(sysDictData.getDictLabel());
                            }
                        }
                    } else {
                        coverageSensorRecordPo.setSystemName("图层系统类型字典错误，请检查字典");
                    }
                }
                //测点编码
                coverageSensorRecordPo.setPointCode(baseSensorVo.getPointCode());
                //测点名称
                coverageSensorRecordPo.setPointName(baseSensorVo.getPointName());
                coverageSensorRecordPo.setUpdateTime(new Date());
                coverageSensorRecordPo.setMineCode(coverageSensorRecordPo.getMineCode() != null ? coverageSensorRecordPo.getMineCode() : null);
                coverageSensorRecordMapper.insert(coverageSensorRecordPo);
            }
        }
        return true;
    }

    /**
     * 根据图层类型获取系统测点列表
     *
     * @param coverageType
     * @return
     */
    @Override
    public List<CoverageSystemListDto> getOsListByType(String coverageType, String mineCode, String companyCode) {
        if (coverageType == null) {
            throw new HuaNengException(Constants.FAIL, "图层信息编码不能为空");
        }
        List<CoverageSystemListDto> coverageSystemListDtoList = new ArrayList<>();
        //安全监控图层
        //获取所有系统的所有测点
        //系统类型
        List<SysDictData> coverageOSTypeList = RedisUtils.getCacheObject(Constants.SYS_DICT_KEY + "biz_mineInfo_coverageOS_type");
        for (SysDictData sysDictData : coverageOSTypeList) {
            CoverageSystemListDto coverageSystemListDto = new CoverageSystemListDto();
            //设置系统编码
            coverageSystemListDto.setOsTypeCode(sysDictData.getDictValue());
            coverageSystemListDto.setOsTypeLabel(sysDictData.getDictLabel());
            //远程调用当前系统
            List<BaseSensorVo> baseListByTypeList = this.getBaseListByType(sysDictData.getDictValue(), mineCode, companyCode);
            if (!baseListByTypeList.isEmpty()) {
                //当前系统内所有测点列表
                //获取当前图层当前系统的已标记的测点
                LambdaQueryWrapper<CoverageSensorRecordPo> recordPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
                //图层编码
                recordPoLambdaQueryWrapper.eq(CoverageSensorRecordPo::getCoverageCode, coverageType);
                //系统编码
                recordPoLambdaQueryWrapper.eq(CoverageSensorRecordPo::getSystemCode, sysDictData.getDictValue());
                recordPoLambdaQueryWrapper.eq(StringUtils.isNotBlank(mineCode), CoverageSensorRecordPo::getMineCode, mineCode);
                List<CoverageSensorRecordPo> coverageSensorRecordPos = coverageSensorRecordMapper.selectList(recordPoLambdaQueryWrapper);

                //遍历一遍
                baseListByTypeList.stream().forEach(BaseSensorVo -> {
                    BaseSensorVo.setSelects(false);
                    for (CoverageSensorRecordPo coverageSensorRecordPo : coverageSensorRecordPos) {
                        //测点编码是否相同
                        if (BaseSensorVo.getPointCode().equals(coverageSensorRecordPo.getPointCode())) {
                            BaseSensorVo.setSelects(true);
                        }
                    }

                });


            } else {
                //查不到当前系统的数据
                baseListByTypeList = new ArrayList<>();
            }
            coverageSystemListDto.setBaseSensorVoList(baseListByTypeList);
            coverageSystemListDtoList.add(coverageSystemListDto);
        }
        return coverageSystemListDtoList;
    }

    /**
     * 图层-获取图层信息列表
     *
     * @param mineCode
     * @return
     */
    @Override
    public List<CoverageListVo> getCoverageList(String mineCode) {
        LambdaQueryWrapper<CoverageSensorLayerPo> coverageSensorLayerPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //查询所有的图层列表
        coverageSensorLayerPoLambdaQueryWrapper.eq(StringUtils.isNotEmpty(mineCode), CoverageSensorLayerPo::getMineCode, mineCode);
        List<CoverageSensorLayerPo> coverageSensorLayerPos = coverageSensorLayerMapper.selectList(coverageSensorLayerPoLambdaQueryWrapper);
        if (coverageSensorLayerPos.isEmpty()) {
            //初始化图层信息列表
            initCoverageList();

            //查询数据库
            List<CoverageSensorLayerPo> coverageSensorLayerPoList = coverageSensorLayerMapper.selectList(coverageSensorLayerPoLambdaQueryWrapper);
            if (coverageSensorLayerPoList.isEmpty()) {
                return new ArrayList<>();
            }
            return coverageSensorLayerPoList.stream().map(t -> {
                CoverageListVo coverageListVo = new CoverageListVo();
                coverageListVo.setCoverageCode(t.getCoverageCode());
                coverageListVo.setCoverageName(t.getCoverageName());
                coverageListVo.setLockFlag(t.getLockFlag());
                return coverageListVo;
            }).sorted(Comparator.comparingInt(vo -> Integer.parseInt(vo.getCoverageCode()))).collect(Collectors.toList());
        }
        return coverageSensorLayerPos.stream().map(t -> {
            CoverageListVo coverageListVo = new CoverageListVo();
            coverageListVo.setCoverageCode(t.getCoverageCode());
            coverageListVo.setCoverageName(t.getCoverageName());
            coverageListVo.setLockFlag(t.getLockFlag());
            return coverageListVo;
        }).sorted(Comparator.comparingInt(vo -> Integer.parseInt(vo.getCoverageCode()))).collect(Collectors.toList());
    }

    /**
     * 初始化图层信息列表
     */
    private void initCoverageList() {
        //进行初始化
        List<CoverageSensorLayerPo> sensorLayerPos = new ArrayList<>();
        CoverageSensorLayerPo coverageSensorLayerPo1 = new CoverageSensorLayerPo("1", "安全监控", "1",0);
        sensorLayerPos.add(coverageSensorLayerPo1);
        CoverageSensorLayerPo coverageSensorLayerPo2 = new CoverageSensorLayerPo("2", "人员定位", "1",1);
        sensorLayerPos.add(coverageSensorLayerPo2);
        CoverageSensorLayerPo coverageSensorLayerPo3 = new CoverageSensorLayerPo("3", "水害监测", "1",2);
        sensorLayerPos.add(coverageSensorLayerPo3);
        CoverageSensorLayerPo coverageSensorLayerPo4 = new CoverageSensorLayerPo("4", "火灾监测", "1",3);
        sensorLayerPos.add(coverageSensorLayerPo4);
        CoverageSensorLayerPo coverageSensorLayerPo5 = new CoverageSensorLayerPo("5", "顶板监测", "1",4);
        sensorLayerPos.add(coverageSensorLayerPo5);
        CoverageSensorLayerPo coverageSensorLayerPo6 = new CoverageSensorLayerPo("6", "冲击地压", "0",5);
        sensorLayerPos.add(coverageSensorLayerPo6);
        CoverageSensorLayerPo coverageSensorLayerPo7 = new CoverageSensorLayerPo("7", "粉尘监测", "0",6);
        sensorLayerPos.add(coverageSensorLayerPo7);
        CoverageSensorLayerPo coverageSensorLayerPo8 = new CoverageSensorLayerPo("8", "工业视频", "0",7);
        sensorLayerPos.add(coverageSensorLayerPo8);
        CoverageSensorLayerPo coverageSensorLayerPo9 = new CoverageSensorLayerPo("9", "应急救援", "0",8);
        sensorLayerPos.add(coverageSensorLayerPo9);
        sensorLayerPos.forEach(coverageSensorLayerPo -> {
            coverageSensorLayerMapper.insert(coverageSensorLayerPo);
        });
    }

    /**
     * 图层-新增图层
     *
     * @param coverageDto
     * @return
     */
    @Override
    public Boolean coverageAdd(CoverageDto coverageDto) {
        //首先获取列表
        LambdaQueryWrapper<CoverageSensorLayerPo> coverageSensorLayerPoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        coverageSensorLayerPoLambdaQueryWrapper.eq(StringUtils.isNotEmpty(coverageDto.getMineCode()), CoverageSensorLayerPo::getMineCode, coverageDto.getMineCode());
        int max = 0;
        List<CoverageSensorLayerPo> coverageSensorLayerPos = coverageSensorLayerMapper.selectList(coverageSensorLayerPoLambdaQueryWrapper);
        if (coverageSensorLayerPos.isEmpty()) {
            initCoverageList();
            coverageSensorLayerPos = coverageSensorLayerMapper.selectList(coverageSensorLayerPoLambdaQueryWrapper);
        }
        for (CoverageSensorLayerPo coverageSensorLayerPo : coverageSensorLayerPos) {
            if (Integer.valueOf(coverageSensorLayerPo.getCoverageCode()) > max) {
                max = Integer.valueOf(coverageSensorLayerPo.getCoverageCode());
            }
        }
        CoverageSensorLayerPo coverageSensorLayerPo = new CoverageSensorLayerPo();
        coverageSensorLayerPo.setCoverageCode(String.valueOf(max + 1));
        coverageSensorLayerPo.setCoverageName(coverageDto.getCoverageName());
        if (coverageDto.getLockFlag().isEmpty() || coverageDto.getLockFlag() == null) {
            coverageSensorLayerPo.setLockFlag("0");
        } else {
            coverageSensorLayerPo.setLockFlag(coverageDto.getLockFlag());
        }
        int insert = coverageSensorLayerMapper.insert(coverageSensorLayerPo);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    /**
     * 图层-加锁或解锁
     *
     * @param coverageCode
     * @param mineCode
     * @return
     */
    @Override
    public Boolean coverageLockFlag(String coverageCode, String mineCode) {
        if (coverageCode == null) {
            throw new HuaNengException(Constants.FAIL, "图层编码不可以为空");
        }
        LambdaQueryWrapper<CoverageSensorLayerPo> queryWrapper = new LambdaQueryWrapper<CoverageSensorLayerPo>()
                .eq(CoverageSensorLayerPo::getCoverageCode, coverageCode)
                .eq(StringUtils.isNotEmpty(mineCode), CoverageSensorLayerPo::getMineCode, mineCode);
        CoverageSensorLayerPo coverageSensorLayerPos = coverageSensorLayerMapper.selectOne(queryWrapper);
        if ("1".equals(coverageSensorLayerPos.getLockFlag())) {
            coverageSensorLayerPos.setLockFlag("0");
        } else if ("0".equals(coverageSensorLayerPos.getLockFlag())) {
            coverageSensorLayerPos.setLockFlag("1");
        } else {
            coverageSensorLayerPos.setLockFlag("0");
        }
        int update = coverageSensorLayerMapper.update(coverageSensorLayerPos, queryWrapper);
        if (update > 1) {
            return true;
        }
        return false;
    }

    /**
     * 图层-批量删除图层
     *
     * @param coverageCodeList
     * @return
     */
    @Override
    public Boolean coverageDelete(List<String> coverageCodeList) {
        coverageCodeList.forEach(s -> {
            coverageSensorLayerMapper.delete(new LambdaQueryWrapper<CoverageSensorLayerPo>().eq(CoverageSensorLayerPo::getCoverageCode, s));
        });
        return true;
    }

    /**
     * 自定义测点-新增测点
     * @param definedSensorDto
     * @return
     */
    @Override
    public Boolean customAdd(DefinedSensorDto definedSensorDto) {
        //获取图层系统类型字典编码
        List<SysDictData> coverageOSList = RedisUtils.getCacheObject(Constants.SYS_DICT_KEY + "biz_mineInfo_coverageOS_type");
        CoverageSensorDefinedPo coverageSensorDefinedPo = new CoverageSensorDefinedPo();
        //系统类型编码及名称
        coverageSensorDefinedPo.setSystemCode(definedSensorDto.getSystemTypeCode());

        //y有字典 读取字典值
        for (SysDictData sysDictData : coverageOSList) {
            if (definedSensorDto.getSystemTypeCode().equals(sysDictData.getDictValue())) {
                coverageSensorDefinedPo.setSystemName(sysDictData.getDictLabel());
            }
        }
        //坐标xyz
        coverageSensorDefinedPo.setCoordinateX(definedSensorDto.getMarkedX());
        coverageSensorDefinedPo.setCoordinateY(definedSensorDto.getMarkedY());
        coverageSensorDefinedPo.setCoordinateZ(definedSensorDto.getMarkedZ());

        coverageSensorDefinedPo.setMineCode(definedSensorDto.getMineCode());

        int insert = coverageSensorDefinedMapper.insert(coverageSensorDefinedPo);
        if (insert > 0) {
            return true;
        }
        return false;
    }

    /**
     * 获取图层树状列表
     * @param mineCode
     * @return
     */
    @Override
    public List<CoverageTreeListVo> getCoverageTreeList(String mineCode) {
        //查询所有图层
        List<CoverageSensorLayerPo> coverageSensorLayerPos = coverageSensorLayerMapper.selectList(new LambdaQueryWrapper<CoverageSensorLayerPo>()
                .eq(StringUtils.isNotBlank(mineCode), CoverageSensorLayerPo::getMineCode, mineCode)
                .orderByAsc(CoverageSensorLayerPo::getOrderId));
        if (coverageSensorLayerPos.isEmpty()) {
            return new ArrayList<>();
        }

        List<CoverageTreeListVo> coverageTreeListVoList = coverageSensorLayerPos.stream().map(t -> {
            CoverageTreeListVo coverageTreeListVo = new CoverageTreeListVo();
            coverageTreeListVo.setCoverageCode(t.getCoverageCode());
            coverageTreeListVo.setCoveragecodeName(t.getCoverageName());
            coverageTreeListVo.setOrderId(t.getOrderId());
            //根据图层编码获取系统列表
            List<CoverageSystemInfoPo> coverageSystemInfoPos = coverageSystemInfoMapper.selectList(
                    new LambdaQueryWrapper<CoverageSystemInfoPo>()
                            .eq(StringUtils.isNotBlank(mineCode), CoverageSystemInfoPo::getMineCode, mineCode)
                            .eq(CoverageSystemInfoPo::getCoverageCode, t.getCoverageCode())
                            .orderByAsc(CoverageSystemInfoPo::getOrderId));

            if (coverageSystemInfoPos.isEmpty()) {
                coverageTreeListVo.setSystemList(new ArrayList<>());
            } else {
                Map<String, CoverageSystemInfoPo> map = new HashMap<>();
                List<CoverageSystemListVo> coverageSystemListVos = new ArrayList<>();
                for (CoverageSystemInfoPo coverageSystemInfoPo : coverageSystemInfoPos) {
                    String systemCode = coverageSystemInfoPo.getSystemCode();
                    //判断系统编码当前是否是 - 结尾
                    if (systemCode.contains("-")) {
                        //先收集整理 汇总带子设备的
                        map.put(systemCode, coverageSystemInfoPo);
                    } else {
                        //没有子设备
                        CoverageSystemListVo coverageSystemListVo = new CoverageSystemListVo();
                        coverageSystemListVo.setSystemCode(coverageSystemInfoPo.getSystemCode());
                        coverageSystemListVo.setSystemName(coverageSystemInfoPo.getSystemName());
                        coverageSystemListVo.setDeviceList(new ArrayList<>());
                        coverageSystemListVo.setOrderId(coverageSystemInfoPo.getOrderId());
                        coverageSystemListVos.add(coverageSystemListVo);
                    }
                }
                Map<String, List<CoverageSystemInfoPo>> map1 = new HashMap<>();

                map.forEach((k, v) -> {
                    String s = removeSubstring(k, "-");
                    if (map1.get(s) == null) {
                        //不存在 则新增
                        List<CoverageSystemInfoPo> list = new ArrayList<>();
                        list.add(v);
                        map1.put(s, list);
                    } else {
                        //存在   则补充
                        //获取v
                        List<CoverageSystemInfoPo> list = map1.get(s);
                        list.add(v);
                        map1.put(s, list);
                    }
                });
                //map1 存储的为子设备集合

                map1.forEach((k, v) -> {
                    //k为二级   v为三级
                    //获取二级
                    CoverageSystemInfoPo coverageSystemInfoPo = v.get(0);
//                    String systemCode = coverageSystemInfoPo.getSystemCode();
                    String systemCode = k + "-*";
                    String systemName = coverageSystemInfoPo.getSystemName();

                    //获取三级
                    List<CoverageDeviceListVo> collect = v.stream().map(ttt -> {
                        CoverageDeviceListVo coverageDeviceListVo = new CoverageDeviceListVo();
                        coverageDeviceListVo.setDeviceCode(ttt.getDeviceCode());
                        coverageDeviceListVo.setDeviceName(ttt.getDeviceName());
                        coverageDeviceListVo.setOrderId(ttt.getOrderId());
                        return coverageDeviceListVo;
                    }).collect(Collectors.toList());


                    CoverageSystemListVo coverageSystemListVo = new CoverageSystemListVo();
                    coverageSystemListVo.setSystemName(systemName);
                    coverageSystemListVo.setSystemCode(systemCode);
                    coverageSystemListVo.setOrderId(coverageSystemInfoPo.getOrderId());
                    coverageSystemListVo.setDeviceList(collect);
                    coverageSystemListVos.add(coverageSystemListVo);
                });

                //二级tree
                coverageTreeListVo.setSystemList(coverageSystemListVos);

            }
            return coverageTreeListVo;
        }).collect(Collectors.toList());


        return coverageTreeListVoList;
    }
    public  String removeSubstring(String originalString, String substring) {
        int index = originalString.indexOf(substring);
        if (index != -1) {
            return originalString.substring(0, index);
        } else {
            return originalString;
        }
    }

}
